import { Module, Store } from "vuex";
import { UserService, Teacher } from "@/api/user";
import Code from "@/consts/common";
import { ElMessage } from "element-plus";
const createModule = <S, R>(store: Module<S, R>) => store as Store<S>;
//https://zhuanlan.zhihu.com/p/143884250
export interface TeacherState {
  total: number;
  loading: boolean;
  teachers: Teacher[];
  page: number;
  size: number;
}

let teacherState: TeacherState = {
  total: 0,
  loading: false,
  teachers: [],
  page: 1,
  size: 15,
};
// 定义一个 module
export default createModule({
  namespaced: true,
  state: teacherState,
  actions: {
    listTeacher({ commit }, params: any) {
      commit("changeLoading");
      UserService.listTeacher(params).then((res) => {
        if (res.code == Code.CODE_SUCCESS) {
          commit("listTeacher", res.data);
        }
        commit("changeLoading");
      });
    },
    pageChange({ commit, dispatch }, data: any) {
      commit("pageChange", data.page);
      dispatch("listTeacher", data);
    },
    pageSizeChange({ commit, dispatch }, data: any) {
      commit("pageSizeChange", data.size);
      commit("pageChange", 1);
      dispatch("listTeacher", data);
    },
    addAfterLoadUserList({ commit }, params: any) {
      UserService.listTeacher(params).then((res) => {
        if (res.code == Code.CODE_SUCCESS) {
          commit("listTeacher", res.data);
        }
      });
    },
    unbing({ commit, dispatch }, data) {
      UserService.unbind(data.telephone).then((res) => {
        if (res.code == Code.CODE_SUCCESS) {
          ElMessage({
            showClose: true,
            message: "解除账户成功",
            type: "success",
          });
          dispatch("listTeacher", data);
        }
      });
    },
  },
  mutations: {
    listTeacher(state, data) {
      state.total = data.total;
      state.teachers = data.data;
    },
    pageChange(state, page) {
      state.page = page;
    },
    changeLoading(state) {
      state.loading = !state.loading;
    },
    pageSizeChange(state, pageSize) {
      state.size = pageSize;
    },
  },
});
